﻿using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Microsoft.Devices;
using Microsoft.Phone;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Media;

namespace MyMP3
{
    public partial class PhotoPage : PhoneApplicationPage
    {

        #region Members

        private byte[] bitmapImageBytes;
        private PhotoCamera camera;

        #endregion

        #region Event Handlers

        private void Save_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            // store picture in global context
            (App.Current as App).ImageBytes = bitmapImageBytes;

            // navigate back to main page
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

        private void Delete_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            bCapture.Click -= Delete_Click;
            bCapture.Click += Capture_Click;
            bCapture.Content = "Capture";

            Camera_IsEnabled(true);

        }

        private void Capture_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            // update button
            bCapture.Click -= Capture_Click;
            bCapture.Click += Delete_Click;
            bCapture.Content = "Delete";

            // capture image
            camera.CaptureImage();

        }

        private void Camera_Initialized(object sender, Microsoft.Devices.CameraOperationCompletedEventArgs e)
        {
            if (e.Succeeded)
            {
                this.Dispatcher.BeginInvoke(delegate()
                {
                    // set status
                    PageTitle.Text = "Camera ON";
                    PageBackground.Background = new SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 0, 100, 0));

                    bCapture.Content = "Capture";
                    bSave.IsEnabled = false;
                });

            }
        }

        private void Camera_CaptureImageAvailable(object sender, Microsoft.Devices.ContentReadyEventArgs e)
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                // local image to build up
                BitmapImage bi = new BitmapImage();

                using (Stream s = e.ImageStream)
                {
                    // save a copy of the stream as a byte array
                    using (MemoryStream ms = new MemoryStream())
                    {
                        s.CopyTo(ms);
                        bitmapImageBytes = ms.ToArray();
                    }

                    // load image to viewer
                    // rewind the stream
                    s.Position = 0;
                    bi.SetSource(s);
                }

                Camera_IsEnabled(false);

                // set image
                iImage.Source = bi;
                iImage.Visibility = Visibility.Visible;

                bCapture.Content = "Delete";
                bSave.IsEnabled = true;
            });

        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            Camera_IsEnabled(true);
        }

        protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            if (camera != null)
            {
                Camera_IsEnabled(false);
            }
        }

        #endregion

        #region Constructors and Initialization

        public PhotoPage()
        {
            InitializeComponent();

        }

        #endregion

        #region Helpers

        private void Camera_IsEnabled(bool flag)
        {
            if (flag)
            {
                // initialize the camera
                camera = new Microsoft.Devices.PhotoCamera(CameraType.Primary);

                // setup handlers
                camera.Initialized += new EventHandler<Microsoft.Devices.CameraOperationCompletedEventArgs>(Camera_Initialized);
                camera.CaptureImageAvailable += new EventHandler<Microsoft.Devices.ContentReadyEventArgs>(Camera_CaptureImageAvailable);

                // set the VideoBrush source to the camera.
                viewfinderBrush.SetSource(camera);
                // set the videobrush background
                iImage.Source = null;
                iImage.Visibility = Visibility.Collapsed;
            }
            else
            {
                // Dispose camera to minimize power consumption and to expedite shutdown.
                camera.Dispose();

                // Release memory, ensure garbage collection.
                camera.Initialized -= Camera_Initialized;
                camera.CaptureImageAvailable -= Camera_CaptureImageAvailable;

                // set status
                PageTitle.Text = "Camera OFF";
                PageBackground.Background = new SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 100, 0, 0));
            }
        }

        #endregion

    }
}